package com.gen.generator.util;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class VelocityUtil {


    /**
     * 渲染 Velocity 模板到文件（IDEA 插件安全版本）
     * @param templatePath
     * @param writer
     * @param data
     * @throws Exception
     */
    public static void renderToFile(String templatePath,
                                    FileWriter writer,
                                    Map<String, Object> data
                                    ) throws Exception {

        // 初始化 Velocity
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.init();

        // 创建上下文
        VelocityContext context = new VelocityContext(data);


        // 使用类加载器读取模板流
        try (InputStream is = VelocityUtil.class.getClassLoader().getResourceAsStream(templatePath)) {
            if (is == null) {
                throw new RuntimeException("模板文件未找到: " + templatePath);
            }
            try (InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
                // 渲染模板到文件
                velocityEngine.evaluate(context, writer, "VelocityLog", reader);
                writer.flush();
            }
        }
    }
}
